import { authService } from "@/services";
import { useRequest } from "ahooks";
import { Button, Flex, Input, InputProps, Spin } from "antd";
import { useState } from "react";

const CheckCode = (props: InputProps) => {
  const { value, onChange, ...inputProps } = props;
  const [val, setVal] = useState("");

  const { data, loading, refresh } = useRequest(
    async () => {
      const response = await authService.getCheckCode();
      return {
        uuid: response.data.uuid,
        img: `data:image/png;base64,${response.data.img}`,
      };
    },
    {
      pollingInterval: 60 * 1000,
    }
  );

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;

    (onChange as any)?.({
      value,
      uuid: data?.uuid,
    });
    setVal(value);
  };

  return (
    <Flex align="center">
      <Input value={val} onChange={handleChange} {...inputProps} />
      <Spin spinning={loading}>
        <Button type="link" onClick={refresh}>
          {data?.img ? <img src={data?.img} /> : null}
        </Button>
      </Spin>
    </Flex>
  );
};

export default CheckCode;
